# -*- coding: utf-8 -*-

from odoo import fields, api
from odoo.exceptions import ValidationError
from odoo_contrib import models


class Settings(models.SchemaModel):
    _name = 'wechat.settings'
    _rec_name = 'appid'

    appid = fields.Char(required=True, string='小程序/公众号appid')
    app_secret = fields.Char(required=True, string='小程序/公众号appsecret')
    miniapp_id = fields.Many2one('wechat.miniapp', required=True, string='微信程序程序实例')
    app_type = fields.Selection(
        [
            (0, '小程序'),
            (1, '公众号'),
        ],
        default=0,
        string='程序类型'
    )
    mp_token = fields.Char(string='公众号token')
    mp_enc_type = fields.Selection(
        [
            (0, '明文模式'),
            (1, '安全模式'),
        ],
        default=0,
        string='公众号消息加密模式',
    )
    mp_aes_key = fields.Char(string='加密key')

    @api.constrains('miniapp_id')
    def check_one_to_one_with_miniapp(self):
        settings_recs = self.search([])
        for settings in settings_recs:
            if settings.miniapp_id == self.miniapp_id and settings.id != self.id:
                raise ValidationError('Only one settings can attached to a mini app')

    @api.constrains('appid')
    def check_appid(self):
        if not self.appid:
            raise ValidationError('appid cannot be empty')

    @api.constrains('app_secret')
    def check_app_secret(self):
        if not self.app_secret:
            raise ValidationError('app secret cannot be empty')

    @api.constrains('mp_token')
    def check_mp_token(self):
        for entry in self:
            if entry.app_type == 1 and not entry.mp_token:
                raise ValidationError('公众号token不能为空')

    @api.constrains('mp_aes_key')
    def check_mp_aes_key(self):
        for entry in self:
            if entry.app_type == 1 and entry.mp_enc_type == 1 and not entry.mp_aes_key:
                raise ValidationError('安全加密模式下加密key不能为空')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if 'mp_token' not in vals:
                vals['mp_token'] = False
            if 'mp_aes_key' not in vals:
                vals['mp_aes_key'] = False
        return super().create(vals_list)

    @api.multi
    def write(self, vals):
        for entry in self:
            if 'mp_token' not in vals:
                vals['mp_token'] = entry.mp_token
            if 'mp_aes_key' not in vals:
                vals['mp_aes_key'] = entry.mp_aes_key
        return super().write(vals)
